<template>
  <div class="tldiv frcc" v-loading="isloading">
    <div class="countdiv">
      共:{{ marks1.data.length }}条记录
      <!-- ;镶嵌线:<el-switch
        v-model="isshowxiangqianxian"
        size="small"
        active-text=""
        inactive-text=""
      /> -->
    </div>
    <!-- <div class="nodatadiv frcc" v-if="marks1.data.length == 0 || marks1.data.length == 1">
      <span v-if="marks1.data.length == 0"> 暂无数据 </span>
      <span v-if="marks1.data.length == 1">
        一条数据无法展示时间轴:{{ marks1.marks[0] }}
      </span>
    </div> -->

    <div class="sldiv"></div>

    <div style="padding: 5px 10px 0px 5px">
      <img
        src="/yxrh/shijianzhou-zuo.png"
        style=""
        alt=""
        class="zuoyoudiv"
        @click="leftclick()"
      />
    </div>

    <vue-slider
      style="flex: 1"
      :min="min"
      :tooltip="'always'"
      :tooltip-placement="'bootom'"
      :tooltip-formatter="formatter2"
      :max="max"
      v-model="tlval"
      :process="false"
      :marks="formatter2mark"
      :data="marks1.data"
      @change="timelinechange"
    >
      <template #dot="{ value, focus }">
        <div :class="['custom-dot', { focus }]">
          <img src="/yxrh/huakuai.png" alt="" class="huakuaidiv" />
        </div>
      </template>
    </vue-slider>

    <div style="padding: 5px 5px 0px 10px">
      <img
        src="/yxrh/shijianzhou-you.png"
        style=""
        alt=""
        class="zuoyoudiv"
        @click="rightclick"
      />
    </div>

    <el-popover placement="bottom-end" :width="600" trigger="hover">
      <template #reference>
        <div class="imglistdiv">
          <el-icon><InfoFilled /></el-icon>
        </div>
      </template>
      <el-table :data="timelinetiflist" height="500">
        <el-table-column width="" property="name" label="名称" />
        <el-table-column width="" property="desc" label="描述" />
        <el-table-column width="" property="remark" label="扩展信息" />
        <el-table-column width="" property="resolution" label="分辨率" />
        <el-table-column width="" property="imgtime" label="时间" />
      </el-table>
    </el-popover>

    <div class="imgoptiondiv fr">
      &nbsp; &nbsp;
      <el-switch
        v-model="shijianzhoujianting"
        size="small"
        @change="shijianzhoujiantingC"
      />
      &nbsp;
      <div class="addonediv" @click="addOne()"></div>
      <div class="addalldiv" @click="addAll()"></div>
      <!-- <div class="addsplitediv" @click="addSplit()"></div> -->
      <div class="adddeletediv" @click="deleteitem()"></div>
    </div>
  </div>
</template>
<script setup>
import VueSlider from "vue-slider-component";
import "vue-slider-component/theme/default.css";

import { ref, reactive, onMounted, watch, onUnmounted } from "vue";
import { ElMessage } from "element-plus";

import useCommon from "./useCommon.js";
import { apiList } from "@/api/apiList";
import dayjs from "dayjs";

import _ from "lodash";

import { useEarthStore } from "@/stores/earth";

let tlval = ref(0);
let min = ref(0);
let max = ref(0);

let marks1 = reactive({
  data: [],
  marks: {},
  marks1: {},
  marks2: {},
});

let Common = useCommon();
let earthStore = useEarthStore();

let shijianzhoujianting = ref(true);

function shijianzhoujiantingC(params) {}

function deleteitem() {
  shijianzhoujianting.value = false
  Common.removeAll()
}

function addSplit(params) {
  let iitem = marks1.marks2[tlval.value];
  if (!_.has(earthStore.pannellist, "rollerpannel")) {
    earthStore.pannellist["rollerpannel"] = {
      name: "roller-pannel",
      options: {},
    };
    setTimeout(() => {
      // window.rollercom

      window.rollercom.exposed.addimage(iitem);
    }, 500);
  } else {
    window.rollercom.exposed.addimage(iitem);
  }
}

function addOne(params) {
  let iitem = marks1.marks2[tlval.value];
  if (!_.has(earthStore.pannellist, "rollerpannel")) {
    earthStore.pannellist["rollerpannel"] = {
      name: "roller-pannel",
      options: {},
    };
    setTimeout(() => {
      // window.rollercom

      window.rollercom.exposed.addimage(iitem);
    }, 500);
  } else {
    window.rollercom.exposed.addimage(iitem);
  }
}

function addAll() {
  if (!_.has(earthStore.pannellist, "rollerpannel")) {
    earthStore.pannellist["rollerpannel"] = {
      name: "roller-pannel",
      options: {},
    };
    setTimeout(() => {
      // window.rollercom

      _.forIn(marks1.marks2, iitem => {
        window.rollercom.exposed.addimage(iitem);
      });
    }, 500);
  } else {
    _.forIn(marks1.marks2, iitem => {
      window.rollercom.exposed.addimage(iitem);
    });
  }
}

function timelinechange(value, index) {
  // console.log(value, index);
}

const getViewExtend = () => {
  let params = {};
  let extend = viewer.camera.computeViewRectangle();
  if (typeof extend === "undefined") {
    //2D下会可能拾取不到坐标，extend返回undefined,因此作如下转换
    let canvas = viewer.scene.canvas;
    let upperLeft = new Cesium.Cartesian2(0, 0); //canvas左上角坐标转2d坐标
    let lowerRight = new Cesium.Cartesian2(canvas.clientWidth, canvas.clientHeight); //canvas右下角坐标转2d坐标

    let ellipsoid = viewer.scene.globe.ellipsoid;
    let upperLeft3 = viewer.camera.pickEllipsoid(upperLeft, ellipsoid); //2D转3D世界坐标

    let lowerRight3 = viewer.camera.pickEllipsoid(lowerRight, ellipsoid); //2D转3D世界坐标

    let upperLeftCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(
      upperLeft3
    ); //3D世界坐标转弧度
    let lowerRightCartographic = viewer.scene.globe.ellipsoid.cartesianToCartographic(
      lowerRight3
    ); //3D世界坐标转弧度

    let minx = Cesium.Math.toDegrees(upperLeftCartographic.longitude); //弧度转经纬度
    let maxx = Cesium.Math.toDegrees(lowerRightCartographic.longitude); //弧度转经纬度

    let miny = Cesium.Math.toDegrees(lowerRightCartographic.latitude); //弧度转经纬度
    let maxy = Cesium.Math.toDegrees(upperLeftCartographic.latitude); //弧度转经纬度
    params.minx = minx;
    params.maxx = maxx;
    params.miny = miny;
    params.maxy = maxy;
  } else {
    //3D获取方式
    params.maxx = Cesium.Math.toDegrees(extend.east);
    params.maxy = Cesium.Math.toDegrees(extend.north);

    params.minx = Cesium.Math.toDegrees(extend.west);
    params.miny = Cesium.Math.toDegrees(extend.south);
  }
  // 返回屏幕所在经纬度范围
  return params;
};

// 获取当前地图瓦片级别
function tileLevel() {
  let tiles = new Set();
  let tilesToRender = viewer.scene.globe._surface._tilesToRender;
  if (Cesium.defined(tilesToRender)) {
    for (let i = 0; i < tilesToRender.length; i++) {
      tiles.add(tilesToRender[i].level);
    }
    return tiles;
  }
}

function getparams(params) {
  let level = tileLevel();
  level = Array.from(level)[0];
  let bbox = getViewExtend();
  return {
    level,
    // geojson,
    bbox,
  };
}

let tmpvalid = "";

// 监听滑块事件 或者最新影像显示事件
watch(tlval, (newVal, oldVal) => {
  let iitem = marks1.marks2[tlval.value];
  // 默认填充值跳过
  earthStore.timelinetime = "未获取到信息";
  if (iitem.lineId == "1111" || iitem.lineId == "2222") {
    return;
  }

  console.log(iitem);

  // 判断需不需要更新
  if (iitem.item.id == tmpvalid) {
    ElMessage.success("最新影像与上期一致");
    return;
  }

  Common.removeAll();

  tmpvalid = iitem.item.id;

  // 对滑块数据进行渲染
  //

  // earthStore.timelinetime = iitem.date;
  // Common.removeAll();
  // setTimeout(() => {
  Common.loadTif(iitem, false);
  // }, 100);
  // if (isshowxiangqianxian.value) {
  //   iitem.lineId.split(",").map(iitem => {
  //     Common.loadLine({ lineId: iitem });
  //   });
  // }

  // Common.loadGeojson()
});

function leftclick(params) {
  let nowindex = 0;
  marks1.data.map((item, index) => {
    if (item == tlval.value) {
      nowindex = index;
    }
  });
  if (nowindex - 1 == -1) {
    return;
  }
  tlval.value = marks1.data[nowindex - 1];
}
function rightclick(params) {
  let nowindex = 0;
  marks1.data.map((item, index) => {
    if (item == tlval.value) {
      nowindex = index;
    }
  });
  if (nowindex + 1 == marks1.data.length) {
    return;
  }
  tlval.value = marks1.data[nowindex + 1];
  // tlval.value =
}

let formatter2 = v => `${marks1.marks1[v]}`;

let formatter2mark = v => {
  return {
    label: `${marks1.marks[v]}`,
    labelStyle: {
      // color: '#3498db'
    },
    // labelActiveStyle: {
    //   color: '#3498db'
    // }
  };
};

let resdata = [
  "2015-5-5",
  "2018-5-5",
  "2018-7-5",
  "2019-3-5",
  "2019-5-5",
  "2019-7-5",
  "2020-9-5",
  "2021-10-5",
  "2022-11-5",
  "2023-3-5",
  "2024-1-5",
];

onMounted(() => {
  moveend();
  cameraChange();
});

let camerahandler = {};

function cameraChange(params) {
  camerahandler = viewer.camera.changed.addEventListener(() => {
    // console.log(viewer.camera.heading,viewer.camera.pitch,viewer.camera.roll);
    demoveend();
    // 当前高度
    // 下面可以写其他的代码了
  });
}

function cameraChangeDis(params) {
  camerahandler();
}

onUnmounted(() => {
  // dragEventDis()
  cameraChangeDis();
  Common.removeAll();
});

function genline(resdata) {
  marks1.data = [];
  marks1.marks = {};
  marks1.marks1 = {};
  marks1.marks2 = {};

  let tmpdata0 = {
    date: "1985-01-01",
    imgtime: "1985-01-01T00:00:00Z",
    lineId: "1111",
  };

  let tmpdata1 = {
    date: dayjs().format("YYYY-MM-DD"),
    imgtime: dayjs().format("YYYY-MM-DD"),
    lineId: "2222",
  };

  if (resdata.length == 0) {
    resdata.push(tmpdata0);
    resdata.push(tmpdata1);
  } else if (resdata.length == 1) {
    let tmpdata = resdata[0];
    resdata = [];
    resdata.push(tmpdata0);
    resdata.push(tmpdata);
  } else {
    // 对重复日期做处理
  }
  let chongfuindexcount = 1;
  let allid = []
  resdata.map((item, index) => {
    let diffval = dayjs(item.imgtime).diff(resdata[0].imgtime, "minutes");

    if (marks1.data.indexOf(diffval) != -1) {
      chongfuindexcount++;
      diffval += chongfuindexcount;
    }

    marks1.data.push(diffval);
    marks1.marks1[marks1.data[marks1.data.length - 1]] = item.imgtime.split("T")[0];
    marks1.marks2[marks1.data[marks1.data.length - 1]] = item;
    if (index == 0 || index == resdata.length - 1) {
      marks1.marks[marks1.data[marks1.data.length - 1]] = item.imgtime.split("-")[0];
    } else {
      marks1.marks[marks1.data[marks1.data.length - 1]] = "";
    }

    if (_.has(item, 'item')) {
      allid.push(item.item.id)
    }

  });

  console.log(marks1.data);

  max.value = marks1.data[marks1.data.length - 1];

  // 判断是否包含上次结果 如果包含就使用上次不包含的话使用最新的

  console.log(allid);
  console.log(tmpvalid);
  if (allid.indexOf(tmpvalid) == -1) {
    console.log(1111);
    tlval.value = marks1.data[marks1.data.length - 1];
  }


  // ElMessage.success(JSON.stringify(marks1))
}

let isloading = ref(false);

let isshowxiangqianxian = ref(false);

let timelinetiflist = ref([]);

function moveend() {
  if (!shijianzhoujianting.value) {
    return;
  }

  console.log("移动结束");
  let sousuoparams = {
    timeRange: "", //时间范围（:分隔）
    sensor: "", //传感器（,分隔）
    wxName: "", //卫星名称
    sunCorner: "", //太阳角
    geojson: [], //矩形框四角点
    shpPath: "", //矢量文件导入
    level: "", //分辨率
  };

  let params = getparams();
  sousuoparams.level = params.level;
  sousuoparams.geojson = params.geojson;

  // // return
  isloading.value = true;

  let bboxstr = `${params.bbox.minx},${params.bbox.miny},${params.bbox.maxx},${params.bbox.maxy}`;

  // let fenbianlv = 20;

  // params['CQL_FILTER'] = `BBOX(geometry,${bboxstr},'EPSG:4326') AND resolution > ${fenbianlv}`

  let searchresolutionstr = Common.getResolution(params.level);

  params[
    "CQL_FILTER"
  ] = `BBOX(linerange,${bboxstr},'EPSG:4326') AND${searchresolutionstr}`;

  params["sortBy"] = "imgtime";
  params["maxFeatures"] = 500;
  apiList.shujuguanli.getYingxiangList(params).then(res => {
    // console.log(res);
    isloading.value = false;
    // dataList.value = res.data;
    let tmpdata = [];

    tmpdata = res.features.map(item => {
      return {
        ...item.properties,
        item: item,
      };
    });
    timelinetiflist.value = tmpdata;
    genline(tmpdata);
  });
}

let demoveend = _.debounce(moveend, 200);
</script>
<style lang="scss">

.juanliandiv{
  position: absolute;
  top: 10px;
  left: 120px;
}

.adddeletediv {
  width: 20px;
  height: 20px;
  background-image: url(/shujuguanli/shanchu.png);
  background-size: 100%;
  &:hover {
    transform: scale(1.1);
  }
  position: absolute;
  top: 2px;
  left: 160px;
}
.addsplitediv {
  width: 20px;
  height: 20px;
  background-image: url(/shujuguanli/juanlian.png);
  background-size: 100%;
  &:hover {
    transform: scale(1.1);
  }
  position: absolute;
  top: 2px;
  left: 125px;
}

.addonediv {
  width: 20px;
  height: 20px;
  background-image: url(/shujuguanli/addone.png);
  background-size: 100%;
  &:hover {
    transform: scale(1.1);
  }
  position: absolute;
  top: 2px;
  left: 60px;
}

.addalldiv {
  width: 17px;
  height: 17px;
  background-image: url(/shujuguanli/addall.png);
  background-size: 100%;
  &:hover {
    transform: scale(1.1);
  }
  position: absolute;
  top: 3px;
  left: 95px;
}

.imgoptiondiv {
  position: absolute;
  // width: 30px;
  // filter: invert(100%) brightness(550%);
  cursor: pointer;
  left: 30px;
  top: 3px;
  z-index: 5;
}

.vue-slider-ltr {
  height: 10px !important;
}
.vue-slider-mark {
  // background-color: #fff!important;
  // background-color: #67C23A!important;
  // width: 10px!important;
}
.vue-slider-mark-step {
  // background-color: #fff!important;
  background-color: #67c23a !important;
  border-radius: 0% !important;
  width: 0.1px !important;
}

.vue-slider-dot-tooltip-inner{
  background-color: #3498db88;
  color: #ffffff88;
  &:hover{
    background-color: #3498db;
    color: #ffffff;
    cursor: pointer;
  }
}
.vue-slider-dot-tooltip-bootom{
  transform: translate(-50%, 80%);
}

.vue-slider-dot-tooltip-inner::after {
  bottom: 100%;
    border-color: transparent;
    border-style: solid;
    border-width: 5px;
    border-bottom-color: inherit;
    transform: translate(-400%, 0%);
}

.nodatadiv {
  position: absolute;
  background-color: #555;
  z-index: 1001;
  width: 100%;
  height: 100%;
  top: 0px;
}
.countdiv {
  position: absolute;
  bottom: 0px;
}
.zuoyoudiv {
  width: 15px;
  filter: invert(100%) brightness(550%);
  cursor: pointer;
}

.imglistdiv {
  position: absolute;
  width: 30px;
  // filter: invert(100%) brightness(550%);
  cursor: pointer;
  left: 10px;
  top: 5px;
}

.custom-dot {
  .huakuaidiv {
    position: absolute;
    width: 20px;
    cursor: pointer;
    top: -3px;
    left: -2px;
  }
}

.tldiv {
  width: 350px;
  height: 80px;
  padding: 5px 15px 0px 15px;
  user-select: none;
  .sldiv {
    position: absolute;
    width: 370px;
    height: 30px;
    border-radius: 10px;
    background-color: #ddd4;
  }
}
</style>
